using System;
using UnityEngine;
using System.Collections.Generic;
using System.IO;
using AOT;
using UnityEngine.Android;

namespace CGF
{
    public class GetPhotoAndroid
    {
        private const int ActivityResultGetPhoto = 1001;
        private static CTask<string> task;
        private static AndroidJavaObject _currentActivity;
        private static AndroidJavaClass _intentClass;
        private static AndroidJavaClass _unityPlayerClass;
        public delegate void ActivityResultDelegate(int requestCode, int resultCode, AndroidJavaObject data);
        private static ActivityResultDelegate _activityResultCallback;

        public static async CTask<string> _GetPhotoFromAlbum(bool isMulti)
        {
            task = CTask<string>.Create();
            if (_unityPlayerClass == null) _unityPlayerClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
            if (_currentActivity == null) _currentActivity = _unityPlayerClass.GetStatic<AndroidJavaObject>("currentActivity");
            if (_intentClass == null) _intentClass = new AndroidJavaClass("android.content.Intent");
            // 创建ACTION_GET_CONTENT Intent
            AndroidJavaObject intent = new AndroidJavaObject("android.content.Intent", _intentClass.GetStatic<string>("ACTION_GET_CONTENT"));
            intent.Call<AndroidJavaObject>("setType", "image/*");
            intent.Call<AndroidJavaObject>("putExtra", _intentClass.GetStatic<string>("EXTRA_ALLOW_MULTIPLE"), isMulti);
            intent.Call<AndroidJavaObject>("addCategory", _intentClass.GetStatic<string>("CATEGORY_OPENABLE"));
            // 创建选择器
            AndroidJavaObject chooser = _intentClass.CallStatic<AndroidJavaObject>("createChooser", intent, "Choose Photo");
            // 注册Activity结果回调
            RegisterActivityResultCallback();
            // 启动Activity
            _currentActivity.Call("startActivityForResult", chooser, ActivityResultGetPhoto);
            return await task;
        }

        private static void RegisterActivityResultCallback()
        {
            if (_activityResultCallback == null)
            {
                _activityResultCallback = OnActivityResultCallback;
            }
            // 获取MainActivity的实例并注册回调
            AndroidJavaClass mainActivityClass = new AndroidJavaClass("cn.helper.MainActivity");
            // 获取activityResultCallbacks列表
            AndroidJavaObject activityResultCallbacks = mainActivityClass.GetStatic<AndroidJavaObject>("activityResultCallbacks");
            // 创建代理对象来接收回调
            var proxy = new ActivityResultProxy(_activityResultCallback);
            // 将回调添加到列表中
            activityResultCallbacks.Call<bool>("add", proxy);
        }

        [MonoPInvokeCallback(typeof(AndroidJavaProxy))]
        private static void OnActivityResultCallback(int requestCode, int resultCode, AndroidJavaObject data)
        {
            if (requestCode == ActivityResultGetPhoto)
            {
                OnActivityResult(data);
            }
        }

        // 自定义代理类来处理Java回调
        private class ActivityResultProxy : AndroidJavaProxy
        {
            private readonly ActivityResultDelegate _callback;
            public ActivityResultProxy(ActivityResultDelegate callback) : base("cn.helper.MainActivity$ActivityResult")
            {
                _callback = callback;
            }
            public void onActivityResult(int requestCode, int resultCode, AndroidJavaObject data)
            {
                _callback?.Invoke(requestCode, resultCode, data);
            }
        }

        private static void OnActivityResult(AndroidJavaObject data)
        {
            if (data != null)
            {
                List<string> uriList = new List<string>();
                // 获取ClipData
                AndroidJavaObject clipData = data.Call<AndroidJavaObject>("getClipData");
                if (clipData != null)
                {
                    // 多选情况
                    int count = clipData.Call<int>("getItemCount");
                    for (int i = 0; i < count; i++)
                    {
                        AndroidJavaObject item = clipData.Call<AndroidJavaObject>("getItemAt", i);
                        AndroidJavaObject uri = item.Call<AndroidJavaObject>("getUri");
                        string uriString = uri.Call<string>("toString");
                        uriList.Add(uriString);
                    }
                }
                else
                {
                    // 单选情况
                    AndroidJavaObject uri = data.Call<AndroidJavaObject>("getData");
                    if (uri != null)
                    {
                        string uriString = uri.Call<string>("toString");
                        uriList.Add(uriString);
                    }
                }
                // 将URI列表转换为JSON数组字符串
                string jsonArray = "[" + string.Join(",", uriList.ConvertAll(uri => "\"" + uri + "\"")) + "]";
                task.SetResult(jsonArray);
            }
        }
        
        public static async CTask<Texture2D> _GetTextureByUri(string uri)
        {
            CTask<Texture2D> task = CTask<Texture2D>.Create();
            using (AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
            using (AndroidJavaObject currentActivity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity"))
            {
                AndroidJavaObject bitmap = GetBitmapBytesFromUri(currentActivity, uri);
                MainThread.Run(() =>
                {
                    Texture2D tex = ConvertAndroidBitmapToTexture2D(bitmap);
                    task.SetResult(tex);
                });
            }
            return await task;
        }

        private static AndroidJavaObject GetBitmapBytesFromUri(AndroidJavaObject context, string uri)
        {
            using (AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
            using (AndroidJavaObject currentActivity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity"))
            {
                // 解析URI
                using (AndroidJavaClass uriClass = new AndroidJavaClass("android.net.Uri"))
                using (AndroidJavaObject uriObj = uriClass.CallStatic<AndroidJavaObject>("parse", uri))
                {
                    // 获取Bitmap
                    AndroidJavaObject bitmap = GetBitmapFromUri(currentActivity, uriObj);
                    return bitmap;
                }
            }
        }
        
        private static AndroidJavaObject GetBitmapFromUri(AndroidJavaObject context, AndroidJavaObject uri)
        {
            using (AndroidJavaObject contentResolver = context.Call<AndroidJavaObject>("getContentResolver"))
            using (AndroidJavaClass bitmapFactory = new AndroidJavaClass("android.graphics.BitmapFactory"))
            {
                // 直接使用BitmapFactory解码URI流
                return bitmapFactory.CallStatic<AndroidJavaObject>("decodeStream", contentResolver.Call<AndroidJavaObject>("openInputStream", uri));
            }
        }
        
        private static Texture2D ConvertAndroidBitmapToTexture2D(AndroidJavaObject androidBitmap)
        {
            if (androidBitmap == null) return null;
            int width = androidBitmap.Call<int>("getWidth");
            int height = androidBitmap.Call<int>("getHeight");
            Texture2D originalTexture = new Texture2D(width, height, TextureFormat.RGBA32, false);
            using (AndroidJavaObject outputStream = new AndroidJavaObject("java.io.ByteArrayOutputStream"))
            {
                androidBitmap.Call<bool>("compress", GetBitmapCompressFormat("PNG"), 80, outputStream);
                byte[] pngBytes = outputStream.Call<byte[]>("toByteArray");
                originalTexture.LoadImage(pngBytes);
                originalTexture.Apply();
                return originalTexture;
            }
        }
        
        private static AndroidJavaObject GetBitmapCompressFormat(string format)
        {
            using (AndroidJavaClass compressFormat = new AndroidJavaClass("android.graphics.Bitmap$CompressFormat"))
            {
                return compressFormat.GetStatic<AndroidJavaObject>(format);
            }
        }
        
        // 权限申请
        public static bool CheckAndRequestAlbumPermission()
        {
            string mediaPermission = "android.permission.READ_MEDIA_IMAGES";
            if (Permission.HasUserAuthorizedPermission(Permission.ExternalStorageRead) || Permission.HasUserAuthorizedPermission(mediaPermission))
            {
                return true;
            }
            try
            {
                Permission.RequestUserPermission(mediaPermission);
            }
            finally { }
            try
            {
                Permission.RequestUserPermission(Permission.ExternalStorageRead);
            }
            finally { }
            return false;
        }
    }
}
